const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url');

const server = http.createServer()

server.on('request', (req, res) => {
  let { pathname: URL, query } = url.parse(req.url, true)
  if (URL === '/') {
    fs.readFile(path.join(__dirname, '/pageA.html'), 'utf-8', function (err, data) {
      if (err) {
        throw err;
      }
      res.writeHead(200, 'success 666', { 'Content-Type': 'text/html' })
      res.end(data);
    });
  } else if (URL === '/data') {  // 首页
    readJSONData('/data.json', function (data) {
      res.statusCode = 200
      res.statusMessage = 'success 666'
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8001');  // CORS解决跨域
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      res.end(JSON.stringify(data));
    });
  } else if (URL === '/jsonp') {
    readJSONData('/data.json', function (data) {
      res.end(`${query.callback}(${JSON.stringify(data)})`)  // jsonp解决跨域
    });
  } else {
    res.statusCode = 404
    res.end('page is not found')
  }
})

server.listen('8000', () => {
  console.log('http://localhost:8000 服务器已启动');
})

function readJSONData(p, fn) {
  fs.readFile(path.join(__dirname, p), 'utf8', (err, data) => {
    if (err) {
      return console.log(err);
    }
    data = JSON.parse(data);
    fn && fn(data);
  })
}